/**
 * fileuploadanddownload
 * UploadUtils.java
 * @author 刘永杰
 * date 2011-9-17
 * @version 1.0
 */
package com.lyjilu.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.lyjilu.model.entity.UploadFile;

/**
 * @author 刘永杰
 * date 2011-9-17
 * @version 1.0
 * 上传处理工具类，主要处理request请求，封装request信息等
 */
public class UploadUtil {
	/**
	 * 处理request，封装表单和上传的文件
	 * 
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public UploadFile parseRequest(HttpServletRequest request) throws Exception {
		request.setCharacterEncoding("UTF-8");
		// 判断是否为上传
		if (ServletFileUpload.isMultipartContent(request)) {
			// 初始一个DiskFileItemFactory
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置临时存放目录
			factory.setRepository(new java.io.File(UploadFile.TEMPREPOSITORY));
			// 设置在案内存中的最大限度
			factory.setSizeThreshold(UploadFile.SIZETHRESHOLD);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置最大上传文件大小
			upload.setSizeMax(UploadFile.SIZEMAX);
			List<FileItem> items = null;
			try {
				// 格式化
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
				if (e instanceof SizeLimitExceededException) {
					throw new RuntimeException("ERROR:上传文件过大");
				}
			}
			// 取得item的迭代对象
			Iterator<FileItem> iter = items.iterator();
			UploadFile uploadFile = new UploadFile();
			Map<String, Object> fields = uploadFile.getFields();
			List<FileItem> files = uploadFile.getFiles();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					String fieldName = new String(item.getFieldName().getBytes(
							"ISO-8859-1"), "UTF-8");
					String fieldValue = new String(item.getString().getBytes(
							"ISO-8859-1"), "UTF-8");
					if (fields.containsKey(fieldName)) {
						Object obj = fields.get(fieldName);
						if (obj instanceof List) {
							List<Object> ob = (List<Object>) obj;
							ob.add(fieldValue);
						} else {
							List<Object> list = new ArrayList<Object>();
							list.add(obj);
							fields.remove(fieldName);
							fields.put(fieldName, list);
						}
					} else {
						fields.put(fieldName, fieldValue);
					}
				} else if (item.get() != null && item.get().length > 0) {
					files.add(item);
				}
			}
			for (Iterator<String> iterator = uploadFile.getFields().keySet()
					.iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				Object obj = uploadFile.getFields().get(key);
				if (obj instanceof List) {
					for (Iterator<Object> iterator2 = ((List<Object>) obj)
							.iterator(); iterator2.hasNext();) {
						Object object = (Object) iterator2.next();
						System.out.println(object);
					}
					// request.
				} else {
					System.out.println(obj);
				}

			}
			request.setAttribute(UploadFile.REQATTRIBUTENAME, uploadFile);
			return uploadFile;
		} else {
			throw new Exception("ERROR:该请求不是上传文件");
		}
	}
}